package com.clss.commandhelper.function.home;

import android.content.pm.PackageManager;

import com.clss.commandhelper.base.BaseJson;
import com.clss.commandhelper.base.BasePresenter;
import com.clss.commandhelper.base.BaseView;
import com.clss.commandhelper.tools.Constant;
import com.clss.commandhelper.tools.eventbus.EventBusHelper;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 *
 * @author liuv
 * @date 2017/11/18
 */

public class HomePresenter extends BasePresenter {
    private static final String TAG = "HomePresenter";

    private HomeView mHomeView;
    private HomeModel mHomeModel;
    private int mVersionCode = 0;


    public void setHomeView(HomeView homeView) {
        this.mHomeView = homeView;
        mContext = mHomeView.getActContext();
    }


    public void checkVersion(boolean isNeedTip){
        if (mHomeModel == null){
            mHomeModel = new HomeModel(mHomeView.getActContext());
        }
        try {
            mVersionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        mHomeModel.checkVersion(mVersionCode, new Callback<BaseJson>() {
            @Override
            public void onResponse(Call<BaseJson> call, Response<BaseJson> response) {
                BaseJson baseJson = response.body();
                EventBusHelper.handleBaseJson(baseJson);
                if (baseJson != null && baseJson.getCode() != null){
                    if (baseJson.getCode() == 1){
                        JsonObject jsonObject = baseJson.getObj().getAsJsonObject();
                        String url = jsonObject.getAsJsonPrimitive("url").getAsString();
                        int leastVersionNumber = jsonObject.getAsJsonPrimitive("leastVersionNumber").getAsInt();
                        //是否必须更新，必须则不可取消
                        boolean mustUpdate = mVersionCode < leastVersionNumber;
                        mHomeView.hasNewVersion(url, !mustUpdate);
                    }else {
                        mHomeView.isLastVersion(isNeedTip);
                    }
                }else {
                    mHomeView.responseError(Constant.UNKNOW_ERROR_CODE, Constant.UNKNOW_ERROR_MESSAGE);
                }
            }

            @Override
            public void onFailure(Call<BaseJson> call, Throwable t) {

            }
        });
    }

    @Override
    public void cancelCall() {

    }

    interface HomeView extends BaseView{
        void hasNewVersion(String url, boolean canCancel);
        void isLastVersion(boolean isNeedTip);
    }
}
